package com.yzy.mall.widget

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import java.lang.Math.min

class MaxHeightRecyclerView : RecyclerView {

    private var maxHeight: Int = -1

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        attrs?.let { attrSet ->
            val attrRes = intArrayOf(android.R.attr.maxHeight)
            val types = context.obtainStyledAttributes(attrSet, attrRes)
            maxHeight = types.getDimensionPixelSize(0, -1)
            types.recycle()
        }
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        val hSize = MeasureSpec.getSize(heightSpec)
        val heightMeasureSpec = if (maxHeight < 0) {
            heightSpec
        } else {
            when (MeasureSpec.getMode(heightSpec)) {
                MeasureSpec.AT_MOST -> MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.AT_MOST)
                MeasureSpec.UNSPECIFIED -> MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
                MeasureSpec.EXACTLY -> MeasureSpec.makeMeasureSpec(min(hSize, maxHeight), MeasureSpec.EXACTLY)
                else -> MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
            }
        }
        super.onMeasure(widthSpec, heightMeasureSpec)
    }
}